<template>
    <basic-container>
        <avue-crud :option="tableOption"
                   :data="list"
                   ref="crud"
                   :page="page"
                   v-model="form"
                   :table-loading="listLoading"
                   @on-load="getList"
                   @search-change="handleFilter"
                   @refresh-change="handleRefreshChange"
                   @row-update="update"
                   @row-del="deletes"
                   @row-save="create">
            <template slot="menu"
                      slot-scope="scope">
                <el-button size="mini"
                           type="text"
                           icon="el-icon-plus"
                           plain
                           @click="handlePermission(scope.row)">权限
                </el-button>
            </template>
        </avue-crud>
        <el-dialog title="分配权限"
                   :visible.sync="dialogPermissionVisible">
            <el-tree class="filter-tree"
                     :data="treeData"
                     :default-checked-keys="checkedKeys"
                     :check-strictly="false"
                     node-key="id"
                     highlight-current
                     :props="defaultProps"
                     show-checkbox
                     ref="menuTree"
                     :filter-node-method="filterNode"
                     default-expand-all>
            </el-tree>
            <div slot="footer"
                 class="dialog-footer">
                <el-button type="primary"
                           @click="updatePermession(roleId)">更 新
                </el-button>
            </div>
        </el-dialog>
    </basic-container>
</template>

<script>
    import {tableOption} from '@/const/role'
    import {roleList,saveRole,updateRole,deleteRole,saveRoleResources} from "@/api/role";
    import {listResources,roleResources} from "@/api/resources";
    export default {
        name: "role_index",
        data() {
            return {
                tableOption: tableOption,
                treeData: [],
                checkedKeys: [],
                defaultProps: {
                    label: "name",
                    value: 'id'
                },
                page: {
                    total: 0, // 总页数
                    currentPage: 1, // 当前页数
                    pageSize: 20 // 每页显示多少条
                },
                resourcesIds: '',
                list: [],
                listLoading: false,
                form: {},
                dialogPermissionVisible:false,
                roleId: undefined,
            }
        },
        methods: {
            getList(){
                roleList().then((response)=>{
                    this.list = response.data.data
                })
            },
            handlePermission(row){
                roleResources(row.id).then((response)=>{
                    this.checkedKeys = response.data.data
                    return listResources()
                }).then((response) => {
                    this.treeData = response.data.data
                    this.checkedKeys = this.resolveAllEunuchNodeId(this.treeData, this.checkedKeys, [])
                    this.dialogPermissionVisible = true
                    this.roleId = row.id
                })
            },
            update(row, done,loading){
                updateRole(this.form).then(()=>{
                    this.getList(this.page);
                    done();
                }).catch(() => {
                    loading();
                });
            },
            create(row, done,loading){
                saveRole(this.form).then((() => {
                    this.getList(this.page);
                    done();
                    this.$notify({
                        title: "成功",
                        message: "创建成功",
                        type: "success",
                        duration: 2000
                    }).catch(() => {
                        loading();
                    });
                }))
            },
            deletes(row,index){
                deleteRole(row.id).then(()=>{
                    this.list.splice(index, 1);
                })
            },
            handleFilter(param) {
                this.page.page = 1;
                this.getList(this.page, param);
            },
            handleRefreshChange() {
                this.getList(this.page)
            },
            updatePermession() {
                this.resourcesIds = this.$refs.menuTree.getCheckedKeys().join(',').concat(',').concat(this.$refs.menuTree.getHalfCheckedKeys().join(','))
                saveRoleResources(this.roleId,this.resourcesIds).then(() => {
                    this.$notify({
                        title: '成功',
                        message: '配置权限成功',
                        type: 'success',
                        duration: 2000
                    })
                    this.dialogPermissionVisible = false
                    this.getList(this.page)
                })
            },
            filterNode(value, data) {
                if (!value) return true
                return data.label.indexOf(value) !== -1
            },
            resolveAllEunuchNodeId(json, idArr, temp) {
                for (let i = 0; i < json.length; i++) {
                    const item = json[i]
                    // 存在子节点，递归遍历;不存在子节点，将json的id添加到临时数组中
                    if (item.children && item.children.length !== 0) {
                        this.resolveAllEunuchNodeId(item.children, idArr, temp)
                    } else {
                        temp.push(idArr.filter(id => id === item.id))
                    }
                }
                return temp
            }
        }
    }
</script>

<style scoped>

</style>
